package com.fh.auth;

import com.alibaba.fastjson.JSON;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @author： qiujunda
 * @date： 2020/12/14 16:20
 */
@Component
@RefreshScope
public class AuthFilter  implements GlobalFilter, Ordered {
    @Resource
    private DiscoveryClient disClient;
    @Resource
    private LoadBalancerClient loadBlance;
    @Value("${authable:false}")
    private boolean authable;
    @Autowired
    private BlackWhiteListConf blackWhiteListConf;

    @Autowired
    private BlackWhiteListHandler blackWhiteListHandler;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        Route route=(Route)exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR) ;
//        System.out.println(blackWhiteListConf);
//        List service=disClient.getServices();
//        List<ServiceInstance> instances= disClient.getInstances("fh-ucas");
//        List<ServiceInstance> instances2= disClient.getInstances("fh-gateway");
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        if(!blackWhiteListHandler.validateBlackList(serverHttpRequest)){
            //是黑名单中的url，直接返回调用方
            StringBuilder logBuilder = new StringBuilder();
            Map map = new HashMap<>();
            map.put("code", 2);
            map.put("message", "请求地址属于黑名单，拒绝访问！");
            String resp = JSON.toJSONString(map);
            logBuilder.append(resp);
            System.out.println(logBuilder.toString());
            DataBuffer bodyDataBuffer = serverHttpResponse.bufferFactory().wrap(resp.getBytes());
            serverHttpResponse.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            return serverHttpResponse.writeWith(Mono.just(bodyDataBuffer));
        }
        if(blackWhiteListHandler.validateWhiteList(serverHttpRequest)){
            //是白名单中的url,直接到下个filter，不进行登录验证了
            return chain.filter(exchange);
        }

        //-------------------------下面开始TOKEN验证--------------------------
        System.out.println("-------------------------------"+serverHttpRequest.getURI());

//        if(authable){
//            StringBuilder logBuilder = new StringBuilder();
//            Map map = new HashMap<>();
//            map.put("code", 2);
//            map.put("message", "签名验证失败");
//            String resp = JSON.toJSONString(map);
//            logBuilder.append(",resp=").append(resp);
//            System.out.println(logBuilder.toString());
//            DataBuffer bodyDataBuffer = serverHttpResponse.bufferFactory().wrap(resp.getBytes());
//            serverHttpResponse.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
//            return serverHttpResponse.writeWith(Mono.just(bodyDataBuffer));
//        }
        if(true){
            return chain.filter(exchange);
        }
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(serverHttpResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                return super.writeWith(body);
            }
        };

        return chain.filter(exchange.mutate().response(decoratedResponse).build());

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
